import { Select, Form, Col } from 'antd';
import { API, ApiModelProps } from "@request/api"
import { useEffect, useState } from 'react';
import { DeepGet } from '@/plugins/support';

interface FormItemSearchProps {
    name: string,
    label: string,
    width?: number,
    onSearch?: Function,
    require: boolean,
    api: keyof ApiModelProps,
    valueKey: string,
    labelKey: string,
}

const FormItemSearch = (props: FormItemSearchProps) => {
    const [options, setOptions] = useState<Object[]>([]);
    const onSearch = async (keywords: string) => {
        try {
            const { api, valueKey, labelKey } = props;
            const { items } = await API[api]({ keywords: keywords });
            setOptions(items);
            // const param: any = {};
            // items.forEach((item: any) => {
            //     param[DeepGet(item, valueKey)] = DeepGet(item, labelKey);
            //     return { [DeepGet(item, valueKey)]: DeepGet(item, labelKey) }
            // })
            // setOptions({ ...param });
        } catch { }
    }
    useEffect(() => {
        onSearch('');
    }, [])
    const getElement = (options: Object[]) => {
        return options.map(item => <Select.Option value={DeepGet(item, props.valueKey)} key={DeepGet(item, props.valueKey)}>
            {DeepGet(item, props.labelKey)}
        </Select.Option>)
        // return Object.entries(options).map(item =>
        //     <Select.Option value={item[0]} key={item[0]}>
        //         {item[1]}
        //     </Select.Option>
        // )
    }
    return (
        <Col style={{ margin: "16px 0" }}>
            <Form.Item wrapperCol={{ span: 5 }} required={props.require} name={props.name} label={props.label}>
                <Select
                    onSearch={onSearch}
                    allowClear
                    showSearch
                    style={{ width: props.width }}
                >
                    {getElement(options)}
                </Select>
            </Form.Item>
        </Col>
    )
}
FormItemSearch.defaultProps = {
    width: 150,
    require: false,
    valueKey: 'id',
    labelKey: 'label'
}


export default FormItemSearch;
export type { FormItemSearchProps };